<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>会员中心-上传文档</title>
    <!-- 引入 Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入 Font Awesome 图标 -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 自定义 Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#1677ff', // 主色调，类似截图中的蓝色
                        lightBg: '#f5f7fa', // 浅背景色
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                },
            }
        }
    </script>
    <!-- 自定义工具类 -->
    <style>
        .content-auto {
            content-visibility: auto;
        }

        .sidebar-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.75rem 1rem;
            border-radius: 0.375rem;
            cursor: pointer;
            transition: all 200ms;
        }

        .sidebar-item.active {
            background-color: #3b82f6;
            color: white;
        }

        .upload-area {
            border: 2px dashed #d1d5db;
            border-radius: 0.375rem;
            padding: 2rem;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            gap: 0.75rem;
            cursor: pointer;
            transition: all 200ms;
        }

        .upload-area:hover {
            border-color: #3b82f6;
            background-color: #eff6ff;
        }

        .category-root {
            color: #6b7280;
        }

        .category-child::before {
            content: "— ";
            color: #9ca3af;
            display: inline-block;
            margin-right: 0.25rem;
        }

        .login-button {
            width: 100%;
            padding: 0.75rem;
            border-radius: 0.5rem;
            background-color: #3b82f6;
            color: white;
            font-weight: 500;
            transition: all 200ms;
        }

        .login-button:hover {
            background-color: rgba(59, 130, 246, 0.9);
        }

        .login-button:focus {
            outline: none;
            ring: 2px solid rgba(59, 130, 246, 0.5);
            ring-offset: 2px;
        }

        /* 弹窗动画类 */
        .scale-95 {
            transform: scale(0.95);
            transition: transform 0.2s ease-out;
        }

        .scale-100 {
            transform: scale(1);
            transition: transform 0.2s ease-out;
        }
    </style>
</head>

<body class="bg-lightBg min-h-screen flex">
    <!-- 登录弹窗 -->
    <div id="loginModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-lg shadow-xl w-full max-w-md overflow-hidden transform transition-all">
            <div class="p-6">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-xl font-bold text-gray-800">会员登录</h2>
                    <button id="closeModalBtn" class="text-gray-500 hover:text-gray-700 focus:outline-none">
                        <i class="fa fa-times text-xl"></i>
                    </button>
                </div>

                <!-- 登录错误信息 -->
                <div id="modalError" class="mb-4 bg-red-50 text-red-700 px-4 py-2 rounded-md hidden">
                    <span id="modalErrorText"></span>
                </div>

                <!-- 登录表单 -->
                <form id="loginForm">
                    <div class="mb-4">
                        <label for="modalUsername" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                        <input type="text" id="modalUsername"
                            class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary transition-all duration-200"
                            placeholder="请输入用户名">
                    </div>

                    <div class="mb-4">
                        <label for="modalPassword" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                        <input type="password" id="modalPassword"
                            class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary transition-all duration-200"
                            placeholder="请输入密码">
                    </div>

                    <button type="button" id="modalLoginBtn"
                        class="w-full py-3 rounded-lg bg-primary text-white font-medium hover:bg-primary/90 transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:ring-offset-2">
                        <i class="fa fa-sign-in mr-2"></i> 登录
                    </button>
                </form>

                <div class="mt-4 text-center">
                    <span class="text-gray-600">还没有账号？</span>
                    <a href="/register.html" class="text-primary hover:underline">立即注册</a>
                </div>
            </div>
        </div>
    </div>
    <!-- 侧边栏 -->
    <aside class="w-64 bg-white shadow-md">
        <div class="p-4">
            <h1 class="text-2xl font-bold text-gray-800">会员中心</h1>
            <!-- 登录按钮 -->
            <button id="showLoginModalBtn" class="login-button w-full mt-4">
                <i class="fa fa-sign-in mr-2"></i> 立即登录
            </button>
        </div>
        <nav class="mt-4">
            <ul>
                <li>
                    <a href="#" class="sidebar-item active">
                        <i class="fa fa-cloud-upload"></i>
                        上传文档
                    </a>
                </li>
                <!-- 新增：文档管理 菜单项 -->
                <li>
                    <a href="documents.html" class="sidebar-item" id="documentsLink">
                        <i class="fa fa-folder-open"></i> <!-- 使用文件夹打开图标，与文档管理语义匹配 -->
                        文档管理
                    </a>
                </li>
                <!-- 新增：公众号管理 菜单项 -->
                <li>
                    <a href="wechat-accounts.html" class="sidebar-item" id="wechatAccountsLink">
                        <i class="fa fa-weixin"></i>
                        公众号管理
                    </a>
                </li>
                <!-- 新增：账号管理 菜单项 -->
                <li>
                    <a href="wechat-account-management.html" class="sidebar-item">
                        <i class="fa fa-user-circle-o"></i>
                        账号管理
                    </a>
                </li>
                <!-- 新增：抓取管理 菜单项 -->
                <li>
                    <a href="scraping.html" class="sidebar-item">
                        <i class="fa fa-scissors"></i>
                        抓取管理
                    </a>
                </li>
                <!-- 新增：数据库配置 菜单项 -->
                <li>
                    <a href="database-config.html" class="sidebar-item">
                        <i class="fa fa-database"></i>
                        数据库配置
                    </a>
                </li>
                <!-- 新增：发布管理 菜单项 -->
                <li>
                    <a href="publish-management.html" class="sidebar-item">
                        <i class="fa fa-paper-plane"></i>
                        发布管理
                    </a>
                </li>
                <li class="logout-item hidden">
                    <a href="#" class="sidebar-item" id="logoutLink">
                        <i class="fa fa-sign-out"></i>
                        退出登录
                    </a>
                </li>
            </ul>
        </nav>
    </aside>

    <!-- 主内容区 -->
    <main class="flex-1 p-8">
        <div class="grid grid-cols-12 gap-8">
            <!-- 左侧表单区 -->
            <div class="col-span-8 bg-white rounded-lg shadow-sm p-6">
                <h2 id="uploadTitle" class="text-xl font-semibold text-gray-800 mb-6">上传免费文档</h2>

                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">文档类型</label>
                    <div class="flex space-x-4" id="documentTypeGroup">
                        <button id="vipDocBtn" class="px-3 py-1 rounded text-gray-600 hover:bg-gray-100"
                            data-type="vip">VIP文档</button>
                        <button id="paidDocBtn" class="px-3 py-1 rounded text-gray-600 hover:bg-gray-100"
                            data-type="pay">付费文档</button>
                        <button id="freeDocBtn" class="px-3 py-1 rounded bg-primary text-white"
                            data-type="free">免费文档</button>
                    </div>
                </div>

                <!-- 付费文档价格设置 (默认隐藏) -->
                <div id="priceContainer" class="mb-4 hidden">
                    <label for="price" class="block text-sm font-medium text-gray-700 mb-2">
                        文档价格 <span class="text-red-500">*</span>
                    </label>
                    <div class="flex items-center space-x-2">
                        <span class="text-gray-600">¥</span>
                        <input type="number" id="price" name="price" min="0" step="0.01"
                            class="w-32 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                            placeholder="请输入价格">
                    </div>
                </div>

                <!-- VIP文档特殊设置 (默认隐藏) -->
                <div id="vipContainer" class="mb-4 hidden">
                    <label class="block text-sm font-medium text-gray-700 mb-2">VIP文档设置</label>
                    <div class="flex items-center space-x-4">
                        <label class="flex items-center">
                            <input type="checkbox" id="isExclusive" name="isExclusive" class="mr-1">
                            <span>仅VIP可见</span>
                        </label>
                    </div>
                </div>

                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">分类方式</label>
                    <div class="flex items-center space-x-4">
                        <label class="flex items-center">
                            <input type="radio" name="categoryType" value="uniform" checked class="mr-1">
                            <span>统一分类</span>
                        </label>
                        <label class="flex items-center">
                            <input type="radio" name="categoryType" value="nonUniform" class="mr-1">
                            <span>不统一分类</span>
                        </label>
                    </div>
                </div>

                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">所属分类</label>
                    <div class="relative">
                        <input type="text" id="categoryDisplay"
                            class="w-full border border-gray-300 rounded-md px-3 py-2 pr-8 focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary cursor-pointer"
                            placeholder="请选择分类" readonly>
                        <i
                            class="fa fa-chevron-down absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500"></i>
                        <div id="categoryDropdown"
                            class="absolute left-0 right-0 mt-1 border border-gray-300 rounded-md bg-white shadow-lg max-h-60 overflow-y-auto hidden">
                            <ul class="category-list">
                                <!-- 分类列表将通过JavaScript动态生成 -->
                            </ul>
                        </div>
                    </div>
                    <script>
                        document.addEventListener('DOMContentLoaded', function () {
                            // 调试日志函数 - 仅保留控制台输出
                            function logDebug(message) {
                                console.log(`[DEBUG] ${message}`);
                            }


                            // DOM元素缓存
                            const categoryDisplay = document.getElementById('categoryDisplay');
                            const categoryDropdown = document.getElementById('categoryDropdown');
                            const categoryList = document.querySelector('.category-list');
                            const hiddenInput = document.getElementById('category');

                            // 元素存在性检查
                            logDebug('分类相关元素检查:');
                            logDebug('- categoryDisplay存在: ' + (categoryDisplay !== null));
                            logDebug('- categoryDropdown存在: ' + (categoryDropdown !== null));
                            logDebug('- categoryList存在: ' + (categoryList !== null));
                            logDebug('- 隐藏输入框存在: ' + (hiddenInput !== null));

                            // 验证必填元素
                            if (!categoryDisplay || !categoryDropdown || !categoryList || !hiddenInput) {
                                logDebug('<span style="color:red;">错误: 关键DOM元素缺失，分类功能无法使用</span>');
                                categoryList.innerHTML = '<li class="text-red-500 py-2 px-3">页面元素异常，请刷新重试</li>';
                                return;
                            }

                            // 加载分类数据（修复请求头问题）
                            window.loadCategories = function () {
                                logDebug('===== 开始加载分类数据 =====');
                                categoryList.innerHTML = '<li class="text-gray-500 py-2 px-3">正在加载分类...</li>';

                                const xhr = new XMLHttpRequest();
                                const apiUrl = '/api/categories';

                                logDebug('准备发送GET请求到: ' + apiUrl);

                                xhr.addEventListener('loadstart', () => logDebug('请求开始发送'));
                                xhr.addEventListener('error', () => {
                                    logDebug('<span style="color:red;">请求发生错误（网络异常）</span>');
                                    categoryList.innerHTML = '<li class="text-red-500 py-2 px-3">分类加载失败，请检查网络连接</li>';
                                });

                                xhr.onreadystatechange = function () {
                                    logDebug(`请求状态: readyState=${xhr.readyState}, status=${xhr.status}`);

                                    if (xhr.readyState === 4) {
                                        if (xhr.status === 200) {
                                            logDebug(`请求成功，响应长度: ${xhr.responseText.length}`);
                                            try {
                                                const categories = JSON.parse(xhr.responseText);
                                                logDebug(`解析成功，分类数量: ${Array.isArray(categories) ? categories.length : '非数组'}`);
                                                // 验证数据格式后渲染
                                                if (validateCategoryData(categories)) {
                                                    renderCategories(categories);
                                                } else {
                                                    categoryList.innerHTML = '<li class="text-red-500 py-2 px-3">分类数据格式非法</li>';
                                                }
                                            } catch (e) {
                                                logDebug(`<span style="color:red;">JSON解析错误: ${e.message}</span>`);
                                                categoryList.innerHTML = '<li class="text-red-500 py-2 px-3">分类数据格式错误</li>';
                                            }
                                        } else {
                                            logDebug(`<span style="color:red;">请求失败，状态码: ${xhr.status}</span>`);
                                            categoryList.innerHTML = `<li class="text-red-500 py-2 px-3">分类加载失败（状态码: ${xhr.status}）</li>`;
                                        }
                                    }
                                };

                                xhr.open('GET', apiUrl, true);
                                // 移除GET请求的Content-Type头（冗余且可能引发问题）
                                try {
                                    xhr.send();
                                    logDebug('请求已发送');
                                } catch (e) {
                                    logDebug(`<span style="color:red;">发送请求时异常: ${e.message}</span>`);
                                    categoryList.innerHTML = '<li class="text-red-500 py-2 px-3">发送请求失败</li>';
                                }
                            };

                            // 验证分类数据格式（关键修复：防止字段缺失导致渲染失败）
                            function validateCategoryData(categories) {
                                if (!Array.isArray(categories)) {
                                    logDebug('<span style="color:red;">数据格式错误：非数组</span>');
                                    return false;
                                }
                                for (let i = 0; i < categories.length; i++) {
                                    const item = categories[i];
                                    const requiredFields = ['id', 'pid', 'name', 'sort'];
                                    const missingFields = requiredFields.filter(field => !(field in item));
                                    if (missingFields.length > 0) {
                                        logDebug(`<span style="color:red;">第${i + 1}条分类缺失字段: ${missingFields.join(',')}</span>`);
                                        return false;
                                    }
                                    // 验证字段类型
                                    if (typeof item.id !== 'number' || typeof item.pid !== 'number' ||
                                        typeof item.name !== 'string' || typeof item.sort !== 'number') {
                                        logDebug(`<span style="color:red;">第${i + 1}条分类字段类型错误</span>`);
                                        return false;
                                    }
                                }
                                return true;
                            }

                            // 渲染分类树（修复默认隐藏问题，添加无二级分类提示）
                            function renderCategories(categories) {
                                categoryList.innerHTML = '';

                                // 构建分类映射和根分类
                                const categoryMap = {};
                                const rootCategories = [];

                                // 初始化分类映射
                                categories.forEach(category => {
                                    categoryMap[category.id] = { ...category, children: [] };
                                });

                                // 构建父子关系
                                categories.forEach(category => {
                                    if (category.pid === 0) {
                                        rootCategories.push(categoryMap[category.id]);
                                    } else if (categoryMap[category.pid]) {
                                        categoryMap[category.pid].children.push(categoryMap[category.id]);
                                    } else {
                                        logDebug(`<span style="color:orange;">警告：分类${category.id}的父分类${category.pid}不存在</span>`);
                                    }
                                });

                                // 排序
                                rootCategories.sort((a, b) => a.sort - b.sort);
                                rootCategories.forEach(root => root.children.sort((a, b) => a.sort - b.sort));

                                // 无分类数据处理
                                if (rootCategories.length === 0) {
                                    categoryList.innerHTML = '<li class="text-gray-500 py-2 px-3">暂无分类数据</li>';
                                    return;
                                }

                                // 生成DOM
                                rootCategories.forEach(rootCategory => {
                                    const rootItem = document.createElement('li');
                                    rootItem.className = 'category-item';

                                    // 一级分类（可展开，添加提示图标）
                                    const rootHeader = document.createElement('div');
                                    rootHeader.className = 'category-header category-root cursor-pointer py-1 px-3 rounded hover:bg-gray-100';
                                    rootHeader.setAttribute('data-id', rootCategory.id);
                                    // 显示二级分类数量
                                    const childCount = rootCategory.children.length;
                                    rootHeader.innerHTML = `
                        <i class="fa fa-folder text-gray-500 mr-2"></i>
                        ${rootCategory.name}
                        <span class="text-xs text-gray-400 ml-2">(${childCount}个子分类)</span>
                    `;

                                    // 展开/折叠逻辑（修复无二级分类时的异常）
                                    rootHeader.addEventListener('click', function () {
                                        const childrenList = this.nextElementSibling;
                                        if (childrenList) {
                                            childrenList.classList.toggle('hidden');
                                            // 切换文件夹图标
                                            const icon = this.querySelector('i');
                                            icon.className = childrenList.classList.contains('hidden')
                                                ? 'fa fa-folder text-gray-500 mr-2'
                                                : 'fa fa-folder-open text-gray-500 mr-2';
                                        }
                                    });

                                    rootItem.appendChild(rootHeader);

                                    // 二级分类列表（默认展开，修复用户感知问题）
                                    if (childCount > 0) {
                                        const childrenList = document.createElement('ul');
                                        childrenList.className = 'category-children ml-6'; // 移除默认hidden类

                                        rootCategory.children.forEach(childCategory => {
                                            const childItem = document.createElement('li');
                                            childItem.className = 'category-item';

                                            const childHeader = document.createElement('div');
                                            childHeader.className = 'category-header category-child cursor-pointer py-1 px-3 rounded hover:bg-gray-100';
                                            childHeader.setAttribute('data-id', childCategory.id);
                                            childHeader.innerHTML = `<i class="fa fa-file-text-o text-gray-500 mr-2"></i>${childCategory.name}`;

                                            // 选择分类逻辑
                                            childHeader.addEventListener('click', function (e) {
                                                e.stopPropagation(); // 防止触发父分类展开/折叠
                                                selectCategory(childCategory.id, childCategory.name);
                                            });

                                            childItem.appendChild(childHeader);
                                            childrenList.appendChild(childItem);
                                        });

                                        rootItem.appendChild(childrenList);
                                    } else {
                                        // 无二级分类提示
                                        const noChildItem = document.createElement('ul');
                                        noChildItem.className = 'category-children ml-6';
                                        noChildItem.innerHTML = '<li class="text-gray-400 py-1 px-3 text-sm">无下级分类</li>';
                                        rootItem.appendChild(noChildItem);
                                    }

                                    categoryList.appendChild(rootItem);
                                });
                            }

                            // 选择分类函数（添加空值校验并修复下拉菜单关闭问题）
                            function selectCategory(categoryId, categoryName) {
                                if (!categoryId || !categoryName) {
                                    logDebug('<span style="color:red;">选择分类失败：ID或名称为空</span>');
                                    return;
                                }
                                categoryDisplay.value = categoryName;
                                hiddenInput.value = categoryId;
                                // 同时设置selectedCategoryId变量，确保表单提交时能正确获取分类ID
                                selectedCategoryId = categoryId;
                                logDebug('选择分类后准备关闭下拉菜单');
                                // 移除hidden类并立即重新添加，确保状态变更
                                categoryDropdown.classList.remove('hidden');
                                categoryDropdown.classList.add('hidden');
                                // 同时设置display属性确保完全隐藏
                                categoryDropdown.style.display = 'none';
                                logDebug(`已选择分类：ID=${categoryId}, 名称=${categoryName}，下拉菜单已关闭`);
                            }

                            // 下拉菜单显示/隐藏逻辑
                            categoryDisplay.addEventListener('click', function (e) {
                                e.stopPropagation(); // 防止触发外部点击事件
                                logDebug('分类输入框点击，当前hidden状态: ' + categoryDropdown.classList.contains('hidden'));
                                categoryDropdown.classList.toggle('hidden');
                                logDebug('切换后hidden状态: ' + categoryDropdown.classList.contains('hidden'));
                                // 强制设置下拉菜单为可见，临时调试用
                                categoryDropdown.style.display = categoryDropdown.classList.contains('hidden') ? 'none' : 'block';
                                logDebug('下拉菜单display属性: ' + categoryDropdown.style.display);
                            });

                            // 点击外部关闭下拉菜单
                            document.addEventListener('click', function (event) {
                                if (!categoryDisplay.contains(event.target) && !categoryDropdown.contains(event.target)) {
                                    categoryDropdown.classList.add('hidden');
                                    logDebug('点击外部区域，关闭下拉菜单');
                                }
                            });

                            // 阻止下拉菜单内部点击冒泡
                            categoryDropdown.addEventListener('click', function (e) {
                                e.stopPropagation();
                            });

                            // 初始化加载分类
                            logDebug('调用loadCategories函数加载分类');
                            window.loadCategories();
                        });
                    </script>
                    <input type="hidden" id="category" name="category" value="">
                </div>

                <div class="mb-4">
                    <label for="title" class="block text-sm font-medium text-gray-700 mb-2">
                        标题 <span class="text-red-500">*</span>
                    </label>
                    <input type="text" id="title" name="title"
                        class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                        placeholder="请输入文档标题">
                </div>

                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-2">封面</label>
                    <button id="coverUpload"
                        class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors">
                        点击上传
                    </button>
                    <p class="mt-2 text-sm text-gray-500">如果未上传封面图，系统会自动截取文档封面</p>
                </div>

                <div>
                    <button id="submitBtn"
                        class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors mr-2">
                        提交
                    </button>
                    <button
                        class="px-4 py-2 border border-gray-300 text-gray-700 rounded-md hover:bg-gray-100 transition-colors">
                        取消
                    </button>
                </div>
            </div>

            <!-- 右侧上传区 -->
            <div class="col-span-4 bg-white rounded-lg shadow-sm p-6">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">文件上传</h3>
                <div id="uploadArea" class="upload-area h-48">
                    <i class="fa fa-cloud-upload text-4xl text-gray-400"></i>
                    <p class="text-gray-500">将文件拖到此处，或</p>
                    <button id="clickUpload" class="text-primary hover:underline">点击上传</button>
                    <input type="file" id="fileInput" name="file" class="hidden"
                        accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.txt">
                </div>
                <p class="mt-3 text-sm text-gray-500">只能上传 doc, docx, xls, xlsx, ppt, pptx, pdf, txt 文件，且不超过50mb</p>
                <div id="filePreview" class="mt-4 hidden">
                    <p class="font-medium text-gray-800">已选择文件：</p>
                    <p id="fileName" class="text-gray-600 mt-1"></p>
                </div>
                <!-- 进度条显示 -->
                <div id="progressContainer" class="mt-4 hidden">
                    <div class="flex justify-between text-sm mb-1">
                        <span>上传进度:</span>
                        <span id="progressPercent">0%</span>
                    </div>
                    <div class="w-full bg-gray-200 rounded-full h-2">
                        <div id="progressBar" class="bg-primary h-2 rounded-full" style="width: 0%"></div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- JavaScript 交互逻辑 -->
    <script>
        // 文件上传相关交互
        const uploadArea = document.getElementById('uploadArea');
        const clickUpload = document.getElementById('clickUpload');
        const fileInput = document.getElementById('fileInput');
        const filePreview = document.getElementById('filePreview');
        const fileName = document.getElementById('fileName');

        // 文档类型切换相关元素
        const documentTypeGroup = document.getElementById('documentTypeGroup');
        const vipDocBtn = document.getElementById('vipDocBtn');
        const paidDocBtn = document.getElementById('paidDocBtn');
        const freeDocBtn = document.getElementById('freeDocBtn');
        const uploadTitle = document.getElementById('uploadTitle');
        const priceContainer = document.getElementById('priceContainer');
        const vipContainer = document.getElementById('vipContainer');

        // 当前选择的文档类型
        let currentDocumentType = 'free';

        // 文档类型切换函数
        function switchDocumentType(type) {
            // 更新当前类型
            currentDocumentType = type;

            // 重置所有按钮样式
            vipDocBtn.className = 'px-3 py-1 rounded text-gray-600 hover:bg-gray-100';
            paidDocBtn.className = 'px-3 py-1 rounded text-gray-600 hover:bg-gray-100';
            freeDocBtn.className = 'px-3 py-1 rounded text-gray-600 hover:bg-gray-100';

            // 根据选择的类型更新UI
            if (type === 'vip') {
                vipDocBtn.className = 'px-3 py-1 rounded bg-primary text-white';
                uploadTitle.textContent = '上传VIP文档';
                vipContainer.classList.add('hidden');
                priceContainer.classList.add('hidden');
            } else if (type === 'pay') {
                paidDocBtn.className = 'px-3 py-1 rounded bg-primary text-white';
                uploadTitle.textContent = '上传付费文档';
                vipContainer.classList.add('hidden');
                priceContainer.classList.remove('hidden');
            } else if (type === 'free') {
                freeDocBtn.className = 'px-3 py-1 rounded bg-primary text-white';
                uploadTitle.textContent = '上传免费文档';
                vipContainer.classList.add('hidden');
                priceContainer.classList.add('hidden');
            }
        }

        // 添加文档类型按钮点击事件
        vipDocBtn.addEventListener('click', () => switchDocumentType('vip'));
        paidDocBtn.addEventListener('click', () => switchDocumentType('pay'));
        freeDocBtn.addEventListener('click', () => switchDocumentType('free'));

        // 点击上传区域或“点击上传”文字，触发文件选择
        uploadArea.addEventListener('click', () => fileInput.click());
        clickUpload.addEventListener('click', (e) => {
            e.stopPropagation();
            fileInput.click();
        });

        // 检查重复标题的函数
        function checkDuplicateTitle(title) {
            if (!title) return;

            const xhr = new XMLHttpRequest();
            xhr.open('GET', `/check-duplicate?title=${encodeURIComponent(title)}`, true);
            
            xhr.onload = function() {
                if (xhr.status === 200) {
                    try {
                        const result = JSON.parse(xhr.responseText);
                        if (result.code === 2 && result.data && result.data.duplicates && result.data.duplicates.length > 0) {
                            // 添加预览窗口的CSS样式
                            const previewStyle = document.createElement('style');
                            previewStyle.textContent = `
                                .preview-window {
                                    position: fixed;
                                    top: 50%;
                                    left: 50%;
                                    transform: translate(-50%, -50%) scale(0.95);
                                    width: 90%;
                                    max-width: 1200px;
                                    height: 80%;
                                    max-height: 800px;
                                    background-color: white;
                                    border-radius: 8px;
                                    box-shadow: 0 10px 50px rgba(0, 0, 0, 0.3);
                                    z-index: 1000;
                                    display: none;
                                    flex-direction: column;
                                    transition: transform 0.3s ease-out;
                                }
                                .preview-window.show {
                                    transform: translate(-50%, -50%) scale(1);
                                }
                                .preview-backdrop {
                                    position: fixed;
                                    top: 0;
                                    left: 0;
                                    right: 0;
                                    bottom: 0;
                                    background-color: rgba(0, 0, 0, 0.5);
                                    z-index: 999;
                                    display: none;
                                }
                                .preview-header {
                                    padding: 10px 15px;
                                    background-color: #f7fafc;
                                    border-bottom: 1px solid #e2e8f0;
                                    display: flex;
                                    justify-content: space-between;
                                    align-items: center;
                                    border-radius: 8px 8px 0 0;
                                }
                                .preview-title {
                                    font-weight: 500;
                                    font-size: 14px;
                                    overflow: hidden;
                                    text-overflow: ellipsis;
                                    white-space: nowrap;
                                    flex: 1;
                                    margin-right: 10px;
                                }
                                .preview-close {
                                    background: none;
                                    border: none;
                                    font-size: 18px;
                                    cursor: pointer;
                                    color: #4a5568;
                                    padding: 0;
                                    width: 24px;
                                    height: 24px;
                                    display: flex;
                                    align-items: center;
                                    justify-content: center;
                                    border-radius: 4px;
                                }
                                .preview-close:hover {
                                    background-color: #e2e8f0;
                                }
                                .preview-content {
                                    flex: 1;
                                    overflow: hidden;
                                    position: relative;
                                }
                                .preview-content iframe {
                                    width: 100%;
                                    height: 100%;
                                    border: none;
                                }
                                .preview-loading {
                                    position: absolute;
                                    top: 0;
                                    left: 0;
                                    width: 100%;
                                    height: 100%;
                                    display: flex;
                                    align-items: center;
                                    justify-content: center;
                                    background-color: #f7fafc;
                                    z-index: 1;
                                }
                                .preview-link {
                                    cursor: pointer;
                                    display: inline-block;
                                    transition: background-color 0.2s;
                                }
                                .preview-link:hover {
                                    background-color: #ebf8ff;
                                }
                            `;
                            document.head.appendChild(previewStyle);
                            
                            // 移除之前可能存在的预览窗口和背景遮罩
                            const existingPreview = document.querySelector('.preview-window');
                            if (existingPreview) {
                                document.body.removeChild(existingPreview);
                            }
                            const existingBackdrop = document.querySelector('.preview-backdrop');
                            if (existingBackdrop) {
                                document.body.removeChild(existingBackdrop);
                            }
                            
                            // 创建背景遮罩
                            const backdrop = document.createElement('div');
                            backdrop.className = 'preview-backdrop';
                            document.body.appendChild(backdrop);
                            
                            // 创建预览窗口
                            const previewWindow = document.createElement('div');
                            previewWindow.className = 'preview-window';
                            previewWindow.innerHTML = `
                                <div class="preview-header">
                                    <div class="preview-title" id="previewTitle"></div>
                                    <button class="preview-close" id="previewCloseBtn">×</button>
                                </div>
                                <div class="preview-content">
                                    <div class="preview-loading" id="previewLoading">
                                        <div style="text-align: center;">
                                            <div style="font-size: 36px; margin-bottom: 10px;">⏳</div>
                                            <div>加载中...</div>
                                        </div>
                                    </div>
                                    <iframe id="previewIframe" sandbox="allow-same-origin allow-scripts allow-popups allow-forms allow-top-navigation-by-user-activation allow-popups-to-escape-sandbox"></iframe>
                                </div>
                            `;
                            document.body.appendChild(previewWindow);
                            
                            // 背景遮罩点击关闭预览窗口
                            backdrop.addEventListener('click', function() {
                                previewWindow.style.display = 'none';
                                backdrop.style.display = 'none';
                                previewWindow.classList.remove('show');
                            });
                            
                            // 添加预览窗口关闭事件
                            document.getElementById('previewCloseBtn').addEventListener('click', function() {
                                previewWindow.classList.remove('show');
                                // 动画结束后隐藏
                                setTimeout(() => {
                                    previewWindow.style.display = 'none';
                                    backdrop.style.display = 'none';
                                }, 300);
                            });
                            
                            // 添加预览窗口链接点击事件处理函数
                            function handlePreviewLinkClick(event) {
                                const target = event.target.closest('.preview-link');
                                if (!target) return;
                                 
                                const originalLink = target.getAttribute('data-link');
                                const title = target.getAttribute('data-title');
                                 
                                // 更新预览窗口标题
                                document.getElementById('previewTitle').textContent = title;
                                 
                                // 显示预览窗口和背景遮罩
                                backdrop.style.display = 'block';
                                previewWindow.style.display = 'flex';
                                // 触发动画
                                setTimeout(() => {
                                    previewWindow.classList.add('show');
                                }, 10);
                                 
                                // 显示加载状态
                                const loadingIndicator = document.getElementById('previewLoading');
                                loadingIndicator.style.display = 'flex';
                                 
                                // 获取iframe元素
                                const iframe = document.getElementById('previewIframe');
                                
                                // 创建或获取错误容器
                                let errorContainer = document.getElementById('previewError');
                                if (!errorContainer) {
                                    errorContainer = document.createElement('div');
                                    errorContainer.id = 'previewError';
                                    errorContainer.className = 'preview-error';
                                    // 将错误容器插入到预览内容中
                                    const previewContent = iframe.parentNode;
                                    previewContent.appendChild(errorContainer);
                                }
                                 
                                // 重置状态
                                iframe.style.display = 'none';
                                errorContainer.style.display = 'none';
                                
                                // 创建第三方查看器URL - 使用方案3：第三方查看器
                                // 添加备用查看器和直接下载选项
                                let viewerUrl = '';
                                const viewerType = document.getElementById('viewerType');
                                
                                // 检测文件类型
                                const isPdf = originalLink.toLowerCase().includes('.pdf');
                                const isOffice = originalLink.toLowerCase().includes('.doc') || 
                                               originalLink.toLowerCase().includes('.docx') ||
                                               originalLink.toLowerCase().includes('.xls') ||
                                               originalLink.toLowerCase().includes('.xlsx') ||
                                               originalLink.toLowerCase().includes('.ppt') ||
                                               originalLink.toLowerCase().includes('.pptx');
                                const isImage = originalLink.toLowerCase().includes('.jpg') || 
                                              originalLink.toLowerCase().includes('.jpeg') || 
                                              originalLink.toLowerCase().includes('.png') || 
                                              originalLink.toLowerCase().includes('.gif') ||
                                              originalLink.toLowerCase().includes('.webp') ||
                                              originalLink.toLowerCase().includes('.bmp');
                                
                                // 针对特定域名的处理策略
                                const isDidaProject = originalLink.includes('didaproject.com');
                                const hasForbiddenError = false; // 将在错误处理时更新
                                
                                // 添加查看器切换选项到预览窗口
                                const previewHeader = document.querySelector('#previewWindow .preview-header');
                                if (!viewerType) {
                                    const viewerSelector = document.createElement('div');
                                    viewerSelector.className = 'viewer-selector';
                                    viewerSelector.style.display = 'flex';
                                    viewerSelector.style.alignItems = 'center';
                                    viewerSelector.style.gap = '15px';
                                    viewerSelector.style.marginLeft = 'auto';
                                    viewerSelector.style.padding = '5px 10px';
                                    viewerSelector.style.backgroundColor = 'rgba(255, 255, 255, 0.9)';
                                    viewerSelector.style.borderRadius = '6px';
                                    
                                    // 构建查看器选项
                                    let viewerOptions = '';
                                    
                                    // 添加PDF特定查看器
                                    if (isPdf) {
                                        viewerOptions += `
                                            <option value="google">Google Docs Viewer</option>
                                            <option value="mozilla">Mozilla PDF.js</option>
                                            <option value="drive">Google Drive</option>
                                            <option value="office">Office Online Viewer</option>
                                        `;
                                    } else if (isOffice) {
                                        viewerOptions += `
                                            <option value="google">Google Docs Viewer</option>
                                            <option value="office">Office Online Viewer</option>
                                        `;
                                    }
                                    
                                    // 添加通用选项
                                    viewerOptions += `
                                        <option value="direct">直接访问(原始链接)</option>
                                        <option value="newtab">新标签页打开</option>
                                        <option value="download">下载文件</option>
                                    `;
                                    
                                    viewerSelector.innerHTML = `
                                        <label for="viewerType" style="font-weight: 500;">查看器:</label>
                                        <select id="viewerType" style="padding: 6px 10px; border-radius: 4px; border: 1px solid #ddd;">
                                            ${viewerOptions}
                                        </select>
                                        <span id="viewStatus" style="font-size: 12px; color: #666; padding: 4px 8px; background-color: #f7fafc; border-radius: 3px;">加载中...</span>
                                    `;
                                    previewHeader.appendChild(viewerSelector);
                                    
                                    // 添加查看器切换事件
                                    document.getElementById('viewerType').addEventListener('change', function() {
                                        const selectedViewer = this.value;
                                        let newUrl = '';
                                        
                                        // 更新状态提示
                                        const viewStatus = document.getElementById('viewStatus');
                                        viewStatus.textContent = '切换查看器...';
                                        
                                        switch(selectedViewer) {
                                            case 'google':
                                                newUrl = `https://docs.google.com/viewer?url=${encodeURIComponent(originalLink)}&embedded=true`;
                                                viewStatus.textContent = '使用Google Docs Viewer';
                                                break;
                                            case 'office':
                                                newUrl = `https://view.officeapps.live.com/op/view.aspx?src=${encodeURIComponent(originalLink)}`;
                                                viewStatus.textContent = '使用Office Online Viewer';
                                                break;
                                            case 'mozilla':
                                                newUrl = `https://mozilla.github.io/pdf.js/web/viewer.html?file=${encodeURIComponent(originalLink)}`;
                                                viewStatus.textContent = '使用Mozilla PDF.js';
                                                break;
                                            case 'drive':
                                                newUrl = `https://drive.google.com/viewerng/viewer?url=${encodeURIComponent(originalLink)}`;
                                                viewStatus.textContent = '使用Google Drive查看';
                                                break;
                                            case 'direct':
                                                newUrl = originalLink;
                                                viewStatus.textContent = '直接访问原始链接';
                                                break;
                                            case 'newtab':
                                                window.open(originalLink, '_blank');
                                                viewStatus.textContent = '已在新标签页打开';
                                                return;
                                            case 'download':
                                                const a = document.createElement('a');
                                                a.href = originalLink;
                                                a.download = '';
                                                a.style.display = 'none';
                                                document.body.appendChild(a);
                                                a.click();
                                                document.body.removeChild(a);
                                                viewStatus.textContent = '开始下载文件';
                                                return;
                                        }
                                        
                                        // 显示加载状态
                                        loadingIndicator.style.display = 'flex';
                                        iframe.style.display = 'none';
                                        errorContainer.style.display = 'none';
                                        
                                        // 设置新的URL
                                        iframe.src = newUrl;
                                    });
                                }
                                
                                // 特殊处理didaproject.com域名的文件，优先尝试不同的查看器
                                const defaultViewer = isDidaProject && isPdf ? 'mozilla' : 'google';
                                
                                // 默认使用第一个可用的查看器，并针对特定域名进行优化
                                if (isPdf) {
                                    // PDF文件提供多种查看选项
                                    viewerUrl = isDidaProject ? 
                                        `https://mozilla.github.io/pdf.js/web/viewer.html?file=${encodeURIComponent(originalLink)}` : 
                                        `https://docs.google.com/viewer?url=${encodeURIComponent(originalLink)}&embedded=true`;
                                } else if (isOffice) {
                                    viewerUrl = `https://docs.google.com/viewer?url=${encodeURIComponent(originalLink)}&embedded=true`;
                                } else if (isImage) {
                                    viewerUrl = originalLink;
                                } else {
                                    viewerUrl = originalLink;
                                }
                                
                                // 更新状态提示
                                if (document.getElementById('viewStatus')) {
                                    const statusText = isDidaProject ? 
                                        '正在尝试绕过访问限制...' : 
                                        '正在加载文档...';
                                    document.getElementById('viewStatus').textContent = statusText;
                                }
                                
                                // 设置iframe的src，使用第三方查看器
                                iframe.src = viewerUrl;
                                
                                // 为iframe设置加载事件
                                iframe.onload = function() {
                                    // 更新状态提示
                                    if (document.getElementById('viewStatus')) {
                                        document.getElementById('viewStatus').textContent = '加载完成';
                                    }
                                    
                                    // 检查是否有错误页面
                                    try {
                                        let contentDocument = null;
                                        try {
                                            contentDocument = iframe.contentDocument || iframe.contentWindow.document;
                                        } catch (e) {
                                            // 跨域访问可能会抛出异常，这是正常的
                                        }
                                        
                                        // 如果能访问contentDocument，检查是否是错误页面
                                        const hasErrorContent = contentDocument && 
                                                              (contentDocument.body && contentDocument.body.textContent && 
                                                               (contentDocument.body.textContent.includes('403') || 
                                                                contentDocument.body.textContent.includes('Forbidden') || 
                                                                contentDocument.body.textContent.includes('Error') ||
                                                                contentDocument.body.textContent.includes('无法查看') ||
                                                                contentDocument.body.textContent.includes('access denied') ||
                                                                contentDocument.body.textContent.includes('拒绝访问')));
                                        
                                        if (hasErrorContent) {
                                            // 标记为禁止访问错误
                                            hasForbiddenError = true;
                                            
                                            // 自动尝试下一个可用的查看器
                                            const viewerSelect = document.getElementById('viewerType');
                                            if (viewerSelect && viewerSelect.options.length > viewerSelect.selectedIndex + 1) {
                                                viewerSelect.selectedIndex++;
                                                viewerSelect.dispatchEvent(new Event('change'));
                                                return;
                                            }
                                            
                                            // 处理错误
                                            const errorMsg = isDidaProject ? 
                                                '该文档受到访问限制，已自动尝试多种查看器。请尝试下载或在新标签页中打开。' : 
                                                '该文档无法在此查看器中打开，请尝试切换其他查看器或下载文件。';
                                            showError(errorMsg);
                                            return;
                                        }
                                    } catch (e) {
                                        // 忽略跨域错误
                                    }
                                    
                                    // 隐藏加载状态
                                    loadingIndicator.style.display = 'none';
                                    // 显示iframe
                                    iframe.style.display = 'block';
                                };
                                
                                // 封装错误显示函数
                                function showError(message) {
                                    loadingIndicator.style.display = 'none';
                                    iframe.style.display = 'none';
                                    errorContainer.style.display = 'block';
                                    errorContainer.style.textAlign = 'center';
                                    errorContainer.style.padding = '40px 20px';
                                    errorContainer.style.backgroundColor = '#f8fafc';
                                    errorContainer.style.width = '100%';
                                    errorContainer.style.height = '100%';
                                    errorContainer.style.minHeight = '300px';
                                    errorContainer.style.display = 'flex';
                                    errorContainer.style.alignItems = 'center';
                                    errorContainer.style.justifyContent = 'center';
                                    
                                    // 更新状态提示
                                    if (document.getElementById('viewStatus')) {
                                        document.getElementById('viewStatus').textContent = '预览失败';
                                    }
                                    
                                    // 添加查看器切换提示
                                    let switchViewerHtml = '';
                                    if (isPdf || isOffice) {
                                        switchViewerHtml = `
                                            <div style="margin: 15px 0; padding: 10px; background-color: #ebf8ff; border-radius: 6px;">
                                                <p style="color: #3182ce; font-weight: 500; margin: 0;">提示：请尝试使用顶部的查看器选择器切换不同的查看方式</p>
                                            </div>
                                        `;
                                    }
                                    
                                    // 针对PDF添加特殊提示
                                    let specialTip = '';
                                    if (isPdf) {
                                        specialTip = `
                                            <div style="margin-top: 15px; padding: 15px; background-color: #fffaf0; border: 1px solid #f6e05e; border-radius: 6px;">
                                                <h4 style="color: #dd6b20; margin-top: 0; margin-bottom: 10px;">PDF查看建议</h4>
                                                <ul style="text-align: left; margin: 0; padding-left: 20px; color: #744210; font-size: 14px;">
                                                    <li>尝试Mozilla PDF.js查看器</li>
                                                    <li>使用Google Drive查看器</li>
                                                    <li>下载文件后在本地查看</li>
                                                </ul>
                                            </div>
                                        `;
                                    }
                                    
                                    // 生成更多操作按钮
                                    let actionButtons = `
                                        <div style="display: flex; flex-wrap: wrap; gap: 10px; justify-content: center; margin-top: 20px;">
                                            <button id="tryNextViewer" style="padding: 10px 20px; background-color: #3182ce; color: white; border: none; border-radius: 6px; font-weight: 500; cursor: pointer;">
                                                尝试下一个查看器
                                            </button>
                                            <a href="${originalLink}" target="_blank" style="display: inline-block; padding: 10px 20px; background-color: #718096; color: white; text-decoration: none; border-radius: 6px; font-weight: 500;">
                                                新标签页打开
                                            </a>
                                            <a href="${originalLink}" download style="display: inline-block; padding: 10px 20px; background-color: #38a169; color: white; text-decoration: none; border-radius: 6px; font-weight: 500;">
                                                下载文件
                                            </a>
                                        </div>
                                    `;
                                    
                                    errorContainer.innerHTML = `
                                        <div style="max-width: 500px; margin: 0 auto;">
                                            <div style="font-size: 48px; margin-bottom: 20px;">🚫</div>
                                            <h3 style="color: #e53e3e; margin-bottom: 15px; font-size: 24px;">预览失败</h3>
                                            <p style="color: #4a5568; margin-bottom: 10px; line-height: 1.6;">${message}</p>
                                            ${switchViewerHtml}
                                            ${specialTip}
                                            ${actionButtons}
                                        </div>
                                    `;
                                    
                                    // 添加尝试下一个查看器的事件
                                    const tryNextBtn = document.getElementById('tryNextViewer');
                                    if (tryNextBtn) {
                                        tryNextBtn.addEventListener('click', function() {
                                            const viewerSelect = document.getElementById('viewerType');
                                            if (viewerSelect && viewerSelect.options.length > viewerSelect.selectedIndex + 1) {
                                                viewerSelect.selectedIndex++;
                                                viewerSelect.dispatchEvent(new Event('change'));
                                            } else {
                                                // 如果已经是最后一个选项，回到第一个
                                                viewerSelect.selectedIndex = 0;
                                                viewerSelect.dispatchEvent(new Event('change'));
                                            }
                                        });
                                    }
                                }
                                
                                // 为iframe设置错误事件
                                iframe.onerror = function() {
                                    showError('无法加载文档。可能是因为跨域限制或文件权限问题。');
                                };
                                
                                // 设置超时检测
                                setTimeout(() => {
                                    // 如果加载指示器仍然显示，说明加载超时
                                    if (loadingIndicator.style.display === 'flex') {
                                        loadingIndicator.style.display = 'none';
                                        iframe.style.display = 'none';
                                        errorContainer.style.display = 'block';
                                        errorContainer.style.textAlign = 'center';
                                        errorContainer.style.padding = '40px 20px';
                                        errorContainer.style.backgroundColor = '#f8fafc';
                                        errorContainer.style.width = '100%';
                                        errorContainer.style.height = '100%';
                                        errorContainer.style.minHeight = '300px';
                                        errorContainer.style.display = 'flex';
                                        errorContainer.style.alignItems = 'center';
                                        errorContainer.style.justifyContent = 'center';
                                        errorContainer.innerHTML = `
                                            <div style="max-width: 400px; margin: 0 auto;">
                                                <div style="font-size: 48px; margin-bottom: 20px;">⏰</div>
                                                <h3 style="color: #e53e3e; margin-bottom: 15px; font-size: 24px;">加载超时</h3>
                                                <p style="color: #4a5568; margin-bottom: 25px; line-height: 1.6;">文档加载超时，请尝试在新窗口中打开。</p>
                                                <a href="${originalLink}" target="_blank" style="display: inline-block; padding: 10px 20px; background-color: #3182ce; color: white; text-decoration: none; border-radius: 6px; font-weight: 500;">
                                                    在新窗口中打开文档
                                                </a>
                                            </div>
                                        `;
                                    }
                                }, 10000); // 10秒超时
                            }
                            
                            // 发现重复标题，显示模态框
                            if (result.data && result.data.duplicates && result.data.duplicates.length > 0) {
                                // 构建模态框HTML
                                const modalHTML = `
                                    <div id="duplicateModal" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
                                        <div class="bg-white rounded-lg shadow-xl max-w-md w-full max-h-[80vh] overflow-hidden">
                                            <div class="p-4 border-b flex justify-between items-center">
                                                <h3 class="text-lg font-medium">发现重复标题的文档</h3>
                                                <button id="closeDuplicateModal" class="text-gray-500 hover:text-gray-700">
                                                    ×
                                                </button>
                                            </div>
                                            <div class="p-4 max-h-[60vh] overflow-y-auto">
                                                <p class="text-gray-600 mb-4">您上传的文档标题与以下文档重复：</p>
                                                <ul class="space-y-2">
                                                    ${result.data.duplicates.map(doc => `
                                                        <li class="p-2 border rounded hover:bg-gray-50">
                                                            <a href="${doc.link}" target="_blank" class="text-blue-600 hover:underline">
                                                                ${doc.title}
                                                            </a>
                                                            <div class="text-sm text-gray-500">文档ID: ${doc.id || '未知'}</div>
                                                        </li>
                                                    `).join('')}
                                                </ul>
                                            </div>
                                        </div>
                                    </div>
                                `;
                                
                                // 创建并添加模态框
                                const modalDiv = document.createElement('div');
                                modalDiv.innerHTML = modalHTML;
                                document.body.appendChild(modalDiv.querySelector('#duplicateModal'));
                                
                                // 关闭按钮事件
                                window.closeCurrentModal = function() {
                                    const modal = document.getElementById('duplicateModal');
                                    if (modal) {
                                        modal.remove();
                                    }
                                };
                                
                                const closeBtn = document.getElementById('closeDuplicateModal');
                                if (closeBtn) {
                                    closeBtn.onclick = window.closeCurrentModal;
                                }
                                
                                // 点击模态框外部关闭
                                const modal = document.getElementById('duplicateModal');
                                if (modal) {
                                    modal.addEventListener('click', function(e) {
                                        if (e.target === modal) {
                                            window.closeCurrentModal();
                                        }
                                    });
                                }
                            }
                        }
                    } catch (error) {
                        console.error('处理重复标题检查响应时出错:', error);
                    }
                }
            };
            
            xhr.onerror = function() {
                console.error('重复标题检查请求失败');
            };
            
            xhr.send();
        }

        // 文件选择后预览并检查重复标题
        fileInput.addEventListener('change', () => {
            if (fileInput.files.length > 0) {
                const file = fileInput.files[0];
                fileName.textContent = file.name;
                filePreview.classList.remove('hidden');

                // 自动将文件名（去除扩展名）填入标题栏
                const titleInput = document.getElementById('title');
                if (!titleInput.value.trim()) {
                    // 提取文件名（去除扩展名）
                    const nameWithoutExtension = file.name.substring(0, file.name.lastIndexOf('.')) || file.name;
                    titleInput.value = nameWithoutExtension;
                    
                    // 检查重复标题
                    checkDuplicateTitle(nameWithoutExtension);
                }
            }
        });
        
        // 标题输入变化时也检查重复标题
        document.getElementById('title').addEventListener('blur', function() {
            const title = this.value.trim();
            if (title) {
                checkDuplicateTitle(title);
            }
        });

        // 封面上传按钮交互
        const coverUpload = document.getElementById('coverUpload');
        coverUpload.addEventListener('click', () => {
            alert('模拟封面上传弹窗，实际项目中可替换为文件选择逻辑');
        });

        // 分类选择逻辑 - 添加一个变量来存储当前选择的分类ID
        let selectedCategoryId = ''; // 默认为空

        // 给所有分类项添加点击事件
        document.querySelectorAll('.category-header.category-child').forEach(item => {
            item.addEventListener('click', () => {
                // 移除其他分类的选中状态
                document.querySelectorAll('.category-header.category-child').forEach(el => {
                    el.classList.remove('bg-primary/10', 'text-primary');
                });

                // 添加当前分类的选中状态
                item.classList.add('bg-primary/10', 'text-primary');

                // 存储选择的分类ID
                selectedCategoryId = item.getAttribute('data-id');
            });
        });

        // 检查登录状态的函数
        function checkLoginStatus() {
            return new Promise((resolve) => {
                // 无论localStorage中是否有登录状态，都向服务器验证真实的登录状态
                console.log('发送请求到服务器验证登录状态');

                // 否则，发送网络请求检查登录状态
                console.log('localStorage中没有有效的登录状态，发送请求到服务器');

                fetch('/check-login', {
                    method: 'GET',
                    credentials: 'same-origin'
                })
                    .then(response => {
                        console.log('check-login响应状态:', response.status);
                        if (!response.ok) {
                            // 即使响应状态不是200，也尝试解析JSON
                            return response.json().catch(() => {
                                throw new Error(`Network response was not ok: ${response.status}`);
                            });
                        }
                        return response.json();
                    })
                    .then(data => {
                        console.log('check-login响应数据:', data);
                        // 返回完整的数据对象，包括isLoggedIn和username
                        if (data.isLoggedIn && data.username) {
                            // 如果登录状态有效，保存到localStorage
                            localStorage.setItem('isLoggedIn', 'true');
                            localStorage.setItem('username', data.username);
                        }
                        resolve(data);
                    })
                    .catch(error => {
                        console.error('检查登录状态请求失败:', error.message || error);
                        // 请求失败时，不应该信任localStorage，返回未登录状态
                        // 清除localStorage中的登录信息
                        localStorage.removeItem('isLoggedIn');
                        localStorage.removeItem('username');
                        resolve({ isLoggedIn: false, username: null });
                    });
            });
        }

        // 根据登录状态更新界面
        async function updateLoginUI() {
            // 添加调试信息
            console.log('开始更新登录状态');

            const loginButton = document.getElementById('showLoginModalBtn');
            console.log('登录按钮元素:', loginButton);

            if (!loginButton) {
                console.log('未找到登录按钮');
                return;
            }

            const loginStatus = await checkLoginStatus();
            console.log('登录状态:', loginStatus);

            // 在页面上显示登录状态信息，方便调试
            let statusInfo = document.getElementById('loginStatusInfo');
            if (!statusInfo) {
                statusInfo = document.createElement('div');
                statusInfo.id = 'loginStatusInfo';
                statusInfo.className = 'text-center text-xs text-gray-500 mt-2';
                loginButton.parentNode.appendChild(statusInfo);
            }

            const logoutItem = document.querySelector('.logout-item');

            if (loginStatus.isLoggedIn && loginStatus.username) {
                console.log('用户已登录，用户名:', loginStatus.username);
                // 已登录，隐藏登录按钮，显示退出登录选项
                if (logoutItem) {
                    logoutItem.classList.remove('hidden');
                }
                loginButton.classList.add('hidden');

                // 添加欢迎信息
                let welcomeElement = document.getElementById('welcomeMessage');
                if (!welcomeElement) {
                    welcomeElement = document.createElement('div');
                    welcomeElement.id = 'welcomeMessage';
                    welcomeElement.className = 'text-center text-gray-600 mt-4 px-4';
                    loginButton.parentNode.appendChild(welcomeElement);
                }
                welcomeElement.innerHTML = `<p class="font-medium">欢迎您，${loginStatus.username}</p>`;
            } else {
                // 未登录，显示登录按钮，隐藏退出登录选项
                if (logoutItem) {
                    logoutItem.classList.add('hidden');
                }
                loginButton.classList.remove('hidden');

                // 移除欢迎信息
                const welcomeElement = document.getElementById('welcomeMessage');
                if (welcomeElement) {
                    welcomeElement.remove();
                }
            }

            // 无论登录状态如何，都确保退出登录链接的事件监听正确绑定
            // 注意：退出登录的具体功能在页面底部的handleLogout函数中实现

        }

        // 提交按钮交互
        const submitBtn = document.getElementById('submitBtn');
        const progressContainer = document.getElementById('progressContainer');
        const progressBar = document.getElementById('progressBar');
        const progressPercent = document.getElementById('progressPercent');

        submitBtn.addEventListener('click', async () => {
            // 先检查登录状态
            const loginStatus = await checkLoginStatus();
            if (!loginStatus.isLoggedIn) {
                // 未登录，显示提示信息
                alert('暂未登录');
                return;
            }

            const title = document.getElementById('title').value;
            const category = selectedCategoryId; // 使用选择的分类ID
            const price = document.getElementById('price')?.value;
            const isExclusive = document.getElementById('isExclusive')?.checked || false;

            // 如果没有选择分类，提示用户
            if (!category) {
                alert('请选择文档分类');
                return;
            }

            if (!title) {
                alert('请输入文档标题');
                return;
            }
            if (!fileInput.files.length) {
                alert('请选择要上传的文件');
                return;
            }

            // 对于付费文档，检查是否输入了价格
            if (currentDocumentType === 'pay' && (!price || parseFloat(price) < 0)) {
                alert('请输入有效的文档价格');
                return;
            }

            // 创建FormData对象
            const formData = new FormData();
            formData.append('title', title);
            formData.append('category', category);
            formData.append('documentType', currentDocumentType);

            // 如果是付费文档，添加价格
            if (currentDocumentType === 'pay') {
                formData.append('price', price);
            }

            formData.append('file', fileInput.files[0]);

            // 显示进度条
            progressContainer.classList.remove('hidden');
            progressBar.style.width = '0%';
            progressPercent.textContent = '0%';

            // 禁用提交按钮防止重复提交
            submitBtn.disabled = true;
            submitBtn.textContent = '上传中...';

            // 发送AJAX请求
            const xhr = new XMLHttpRequest();

            // 监听上传进度
            xhr.upload.addEventListener('progress', (e) => {
                if (e.lengthComputable) {
                    const percent = Math.round((e.loaded / e.total) * 100);
                    progressBar.style.width = percent + '%';
                    progressPercent.textContent = percent + '%';
                }
            });

            // 监听请求完成
            xhr.addEventListener('load', () => {
                // 启用提交按钮
                submitBtn.disabled = false;
                submitBtn.textContent = '提交';

                // 隐藏进度条
                progressContainer.classList.add('hidden');

                // 处理响应
                if (xhr.status === 200) {
                    try {
                        const result = JSON.parse(xhr.responseText);
                        if (result.code === 0) {
                            alert('上传成功！' + result.message);
                            // 重置表单
                            resetForm();
                        } else if (result.code === 2) {
                            // 提交时不再显示重复文件弹窗，只显示提示信息
                            if (result.data && result.data.duplicates && result.data.duplicates.length > 0) {
                                // 直接显示提示信息，不显示弹窗
                                alert('注意：发现重复标题的文档，但已继续上传。');
                                // 重置表单
                                resetForm();
                            } else {
                                alert('上传失败：' + result.message);
                            }
                        } else {
                            alert('上传失败：' + result.message);
                        }
                    } catch (error) {
                        alert('上传成功，但处理响应时出错');
                    }
                } else {
                    alert('上传失败，服务器返回错误：' + xhr.status);
                }
            });

            // 监听请求错误
            xhr.addEventListener('error', () => {
                submitBtn.disabled = false;
                submitBtn.textContent = '提交';
                progressContainer.classList.add('hidden');
                alert('网络错误，请稍后重试');
            });

            // 发送POST请求到FileUploadServlet
            xhr.open('POST', '/upload', true);
            xhr.send(formData);
        });

        // 分类加载函数已在页面上方定义
        // 此处不再重复定义，避免函数覆盖

        // 构建分类树HTML
        function buildCategoryTreeHTML(categories) {
            const categoryList = document.querySelector('.category-list');
            categoryList.innerHTML = '';

            categories.forEach(category => {
                // 创建一级分类项
                const categoryItem = document.createElement('li');
                categoryItem.className = 'category-item';

                // 创建一级分类标题
                const rootHeader = document.createElement('div');
                rootHeader.className = 'category-header category-root cursor-pointer py-1 px-3 rounded';
                rootHeader.setAttribute('data-id', category.id);
                rootHeader.innerHTML = `
                    <i class="fa fa-folder text-gray-500 mr-2"></i>
                    ${category.name}
                `;

                categoryItem.appendChild(rootHeader);

                // 如果有子分类，创建子分类列表
                if (category.children && category.children.length > 0) {
                    const childrenList = document.createElement('ul');
                    childrenList.className = 'category-children ml-6 hidden';

                    category.children.forEach(child => {
                        const childItem = document.createElement('li');
                        childItem.className = 'category-item';

                        const childHeader = document.createElement('div');
                        childHeader.className = 'category-header category-child cursor-pointer py-1 px-3 rounded hover:bg-gray-100';
                        childHeader.setAttribute('data-id', child.id);
                        childHeader.innerHTML = `
                            <i class="fa fa-file-text-o text-gray-500 mr-2"></i>
                            ${child.name}
                        `;

                        childItem.appendChild(childHeader);
                        childrenList.appendChild(childItem);
                    });

                    categoryItem.appendChild(childrenList);
                }

                categoryList.appendChild(categoryItem);
            });

            // 绑定事件监听器
            bindCategoryEvents();
        }

        // 绑定分类事件监听器
        function bindCategoryEvents() {
            const categoryDisplay = document.getElementById('categoryDisplay');
            const categoryDropdown = document.getElementById('categoryDropdown');
            const categoryInput = document.getElementById('category');

            // 为所有一级分类添加点击事件（仅用于展开/折叠，不能选中）
            const rootCategories = document.querySelectorAll('.category-root');
            rootCategories.forEach(header => {
                header.addEventListener('click', function (e) {
                    e.stopPropagation();
                    const item = this.parentElement;
                    const children = item.querySelector('.category-children');

                    // 如果有子分类，切换展开/折叠状态
                    if (children) {
                        const icon = this.querySelector('i');
                        if (children.classList.contains('hidden')) {
                            children.classList.remove('hidden');
                            icon.className = 'fa fa-folder-open text-primary mr-2';
                        } else {
                            children.classList.add('hidden');
                            icon.className = 'fa fa-folder text-gray-500 mr-2';
                        }
                    }
                });
            });

            // 为所有二级分类添加点击事件以选择分类
            const childCategories = document.querySelectorAll('.category-child');
            childCategories.forEach(header => {
                header.addEventListener('click', function (e) {
                    e.stopPropagation();

                    // 移除其他选中项的样式
                    document.querySelectorAll('.category-child').forEach(h => {
                        h.classList.remove('bg-primary', 'text-white');
                        const icon = h.querySelector('i');
                        icon.className = 'fa fa-file-text-o text-gray-500 mr-2';
                    });

                    // 添加当前选中项的样式
                    this.classList.add('bg-primary', 'text-white');
                    const icon = this.querySelector('i');
                    icon.className = 'fa fa-file-text-o text-white mr-2';

                    // 设置选中的分类ID和显示文本
                    const categoryId = this.getAttribute('data-id');
                    const categoryName = this.textContent.trim();
                    categoryInput.value = categoryId;
                    categoryDisplay.value = categoryName;

                    // 关闭下拉菜单
                    categoryDropdown.classList.add('hidden');
                });
            });
        }

        // 下拉菜单分类交互逻辑
        function initCategoryDropdown() {
            const categoryDisplay = document.getElementById('categoryDisplay');
            const categoryDropdown = document.getElementById('categoryDropdown');

            // 点击输入框显示/隐藏下拉菜单
            categoryDisplay.addEventListener('click', function (e) {
                e.stopPropagation();
                categoryDropdown.classList.toggle('hidden');
            });

            // 点击其他区域关闭下拉菜单
            document.addEventListener('click', function (e) {
                if (!categoryDisplay.contains(e.target) && !categoryDropdown.contains(e.target)) {
                    categoryDropdown.classList.add('hidden');
                }
            });

            // 分类数据已在页面上方的DOMContentLoaded事件中加载
            // 此处不再重复加载，避免冲突
        }

        // 初始化下拉菜单分类
        document.addEventListener('DOMContentLoaded', function () {
            // 获取DOM元素
            const loginModal = document.getElementById('loginModal');
            const showLoginModalBtn = document.getElementById('showLoginModalBtn');
            const closeModalBtn = document.getElementById('closeModalBtn');
            const modalLoginBtn = document.getElementById('modalLoginBtn');
            const modalError = document.getElementById('modalError');
            const modalErrorText = document.getElementById('modalErrorText');

            // 显示登录弹窗
            function showLoginModal() {
                loginModal.classList.remove('hidden');
                // 添加动画效果
                const modalContent = loginModal.querySelector('div');
                modalContent.classList.add('scale-100');
                modalContent.classList.remove('scale-95');
            }

            // 隐藏登录弹窗
            function hideLoginModal() {
                const modalContent = loginModal.querySelector('div');
                modalContent.classList.add('scale-95');
                modalContent.classList.remove('scale-100');
                setTimeout(() => {
                    loginModal.classList.add('hidden');
                    // 隐藏错误信息并重置表单
                    modalError.classList.add('hidden');
                    document.getElementById('loginForm').reset();
                }, 200);
            }

            // 点击登录按钮跳转到登录页面
            showLoginModalBtn.addEventListener('click', function () {
                window.location.href = '/login.html';
            });

            // 点击关闭按钮隐藏弹窗
            closeModalBtn.addEventListener('click', hideLoginModal);

            // 点击弹窗外部区域隐藏弹窗
            loginModal.addEventListener('click', function (event) {
                if (event.target === loginModal) {
                    hideLoginModal();
                }
            });

            // 弹窗内的登录功能
            modalLoginBtn.addEventListener('click', function () {
                const username = document.getElementById('modalUsername').value;
                const password = document.getElementById('modalPassword').value;

                if (!username || !password) {
                    modalErrorText.textContent = '用户名和密码不能为空';
                    modalError.classList.remove('hidden');
                    return;
                }

                // 创建URL参数
                const params = new URLSearchParams();
                params.append('username', username);
                params.append('password', password);
                params.append('rememberMe', 'off'); // 弹窗登录默认不记住密码

                // 显示加载状态
                modalLoginBtn.disabled = true;
                modalLoginBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 登录中...';
                modalError.classList.add('hidden');

                // 发送登录请求
                fetch('/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: params
                })
                    .then(response => response.json())
                    .then(data => {
                        modalLoginBtn.disabled = false;
                        modalLoginBtn.innerHTML = '<i class="fa fa-sign-in mr-2"></i> 登录';

                        if (data.code === 0) {
                            // 登录成功，隐藏弹窗并更新登录状态
                            hideLoginModal();
                            updateLoginStatus().then(() => {
                                // 显示成功提示
                                alert('登录成功！');
                            });
                        } else {
                            // 登录失败，显示错误信息
                            modalErrorText.textContent = data.message || '登录失败，请检查用户名和密码';
                            modalError.classList.remove('hidden');
                        }
                    })
                    .catch(error => {
                        console.error('登录请求失败:', error);
                        modalLoginBtn.disabled = false;
                        modalLoginBtn.innerHTML = '<i class="fa fa-sign-in mr-2"></i> 登录';
                        modalErrorText.textContent = '网络错误，请稍后再试';
                        modalError.classList.remove('hidden');
                    });
            });

            // 初始化分类下拉菜单
            initCategoryDropdown();
            // 页面加载时检查登录状态并更新界面
            updateLoginUI();
        });

        // 重置表单函数
        function resetForm() {
            document.getElementById('title').value = '';
            document.getElementById('category').value = '';

            // 重置文档类型为免费文档
            switchDocumentType('free');

            // 重置价格设置
            if (document.getElementById('price')) {
                document.getElementById('price').value = '';
            }

            // 重置分类选中状态
            document.querySelectorAll('.category-header').forEach(header => {
                header.classList.remove('bg-primary', 'text-white');
                const icon = header.querySelector('i');
                if (header.classList.contains('category-root')) {
                    if (icon.classList.contains('fa-folder-open')) {
                        icon.className = 'fa fa-folder-open text-gray-500 mr-2';
                    } else {
                        icon.className = 'fa fa-folder text-gray-500 mr-2';
                    }
                } else {
                    icon.className = 'fa fa-file-text-o text-gray-500 mr-2';
                }
            });

            // 重置分类显示输入框
            document.getElementById('categoryDisplay').value = '';

            // 关闭下拉菜单
            document.getElementById('categoryDropdown').classList.add('hidden');

            fileInput.value = '';
            filePreview.classList.add('hidden');
            fileName.textContent = '';
        }

        // 文档管理链接点击事件
        document.getElementById('documentsLink').addEventListener('click', async function (e) {
            e.preventDefault();

            // 先检查登录状态
            const loginStatus = await checkLoginStatus();
            if (!loginStatus.isLoggedIn) {
                // 未登录，显示提示信息
                alert('暂未登录');
                return;
            }

            // 已登录，正常跳转
            window.location.href = 'documents.html';
        });

        // 公众号管理链接点击事件
        document.getElementById('wechatAccountsLink').addEventListener('click', async function (e) {
            e.preventDefault();

            // 先检查登录状态
            const loginStatus = await checkLoginStatus();
            if (!loginStatus.isLoggedIn) {
                // 未登录，显示提示信息
                alert('暂未登录');
                return;
            }

            // 已登录，正常跳转
            window.location.href = 'wechat-accounts.html';
        });

        // 退出登录功能
        function handleLogout() {
            if (confirm('确定要退出登录吗？')) {
                // 调用后端logout接口
                fetch('/logout', {
                    method: 'POST',
                    credentials: 'same-origin'
                })
                    .then(response => {
                        // 无论后端响应如何，都清除localStorage
                        localStorage.removeItem('isLoggedIn');
                        localStorage.removeItem('username');

                        // 更新UI
                        updateLoginUI();

                        // 显示提示信息
                        alert('退出登录成功！');

                        // 刷新页面确保状态完全重置
                        window.location.reload();
                    })
                    .catch(error => {
                        console.error('退出登录请求失败:', error);
                        // 即使请求失败，也清除localStorage
                        localStorage.removeItem('isLoggedIn');
                        localStorage.removeItem('username');

                        // 更新UI
                        updateLoginUI();

                        // 显示提示信息
                        alert('已清除本地登录状态！');
                    });
            }
        }

        // 为退出登录链接添加事件监听
        const logoutLink = document.getElementById('logoutLink');
        if (logoutLink) {
            logoutLink.addEventListener('click', function (e) {
                e.preventDefault();
                handleLogout();
            });
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function () {
            console.log('DOM内容已加载完成，开始初始化页面...');
            // 检查并更新登录状态
            updateLoginUI();
            // 加载分类数据
            console.log('调用loadCategories函数加载分类数据...');
            loadCategories();
        });
    </script>
</body>

</html>